class Emitter {
  constructor() {
    this.events = {};
  }

  on(type, handler) {
    
    if (!this.events[type]) {
      this.events[type] = [];
    }
    
    this.events[type].push(handler);
    return this; // 返回自身以支持链式调用
  }

  off(type, handler) {
    if (!this.events[type]) return;
    if (!handler) {
      delete this.events[type];
      return;
    }
    const index = this.events[type].indexOf(handler);
    if (index !== -1) {
      this.events[type].splice(index, 1);
    }
  }

  emit(type, data) {
    console.log(this.events[type],'type')
    if (this.events[type]) {
      this.events[type].forEach((handler) => handler(data));
    }
  }

  once(type, handler) {
    const onceHandler = (...args) => {
      this.off(type, onceHandler);
      handler(...args);
    };
    this.on(type, onceHandler);
  }
}

// // 使用示例：
// const emitter = new Emitter();

// const logData = (data) => console.log('Received data:', data);

// emitter.on('myEvent', logData);
// emitter.emit('myEvent', { key: 'value' });

// // 只触发一次的事件监听器
// emitter.once('oneTimeEvent', (data) => console.log('One time event triggered:', data));
// emitter.emit('oneTimeEvent', { single: 'use' });